package com.auxgroup.hr.front.site.co.process;

import com.auxgroup.hr.front.commons.BaseRetCode;
import com.auxgroup.hr.front.commons.enums.WfStatusEnum;
import com.auxgroup.hr.front.commons.enums.WfTypeEnum;
import com.auxgroup.hr.front.commons.utils.ObjectFieldUtils;
import com.auxgroup.hr.front.commons.vo.BaseResponseVO;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dao.domain.JobCurrPrimary;
import com.auxgroup.hr.front.dao.domain.PsCWfEmpVw;
import com.auxgroup.hr.front.dao.domain.PsCWfGoutDtl;
import com.auxgroup.hr.front.dao.domain.PsCWfGoutHdr;
import com.auxgroup.hr.front.dao.repository.PsCWfEmpVwRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfGoutHdrRepository;
import com.auxgroup.hr.front.service.process.WfGoutHdrService;
import com.auxgroup.hr.front.site.co.BaseWfCO;
import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import com.auxgroup.hr.front.site.vo.process.WfOutHdrRespVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 外出申请CO
 *
 * @author wangchangyun
 * @version 创建时间：180527
 */
@RestController
@RequestMapping("${auxgroup.hr.contextPath}/wfouthdr")
public class WfOutHdrCO extends BaseWfCO {

    private static final Logger logger = LoggerFactory.getLogger(WfOutHdrCO.class);

    @Autowired
    private WfGoutHdrService wfGoutHdrService;
    @Autowired
    private PsCWfEmpVwRepository psCWfEmpVwRepository;
    @Autowired
    private PsCWfGoutHdrRepository psCWfGoutHdrRepository;

    @GetMapping(value = "/getYbh")
    public BaseResponseVO getYbhInfo() {
        int noYbhNumber = 0;
        int totalNumber = 0;
        List noYbhNumberList = psCWfGoutHdrRepository.countBenchmarkingNoYbhNumber();
        List totalNumberList = psCWfGoutHdrRepository.countBenchmarkingNumber();
        if (noYbhNumberList != null && noYbhNumberList.size() > 0 && noYbhNumberList.get(0) != null) {
            noYbhNumber = ((BigDecimal) noYbhNumberList.get(0)).intValue();
        }
        if (totalNumberList != null && totalNumberList.size() > 0 && totalNumberList.get(0) != null) {
            totalNumber = ((BigDecimal) totalNumberList.get(0)).intValue();
        }
        Benchmarking benchmarking = new Benchmarking();
        if (totalNumber == 0) {
            benchmarking.setTotalNumber(0);
            benchmarking.setNoYhbNumber(0);
            benchmarking.setNoYbhRate("0");
        } else {

            benchmarking.setTotalNumber(totalNumber);
            benchmarking.setNoYhbNumber(noYbhNumber);
            benchmarking.setNoYbhRate(Math.round(noYbhNumber * 10000.0 / totalNumber) * 1.0 / 100 + "");
        }
        return buildRespone(benchmarking);
    }

    @GetMapping(value = "/getWfOutHdr")
    public BaseResponseVO getWfOutHdr(String cTransactionNbr, @SessionGain("user") UserDTO user) {
        if (StringUtils.isBlank(cTransactionNbr)) {
            return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
        }
        PsCWfGoutHdr outHdr = wfGoutHdrService.getWfInfo(cTransactionNbr);
        if (outHdr == null) {
            return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_NOT_EXIST);
        }
        //20190505 添加对列表字段
        WfOutHdrRespVO respVO = objectMapper.map(outHdr, WfOutHdrRespVO.class);
        List<PsCWfGoutDtl> dtls = wfGoutHdrService.queryByNbr(cTransactionNbr);
        respVO.setAppliers(
                dtls.stream().map(dtl -> {
                            JobCurrPrimary primary = new JobCurrPrimary();
                            primary.setEmplid(dtl.getEmplid());
                            primary.setEmplRcd(new BigDecimal(0));
                            PsCWfEmpVw vw = psCWfEmpVwRepository.findOne(primary);
                            WfOutHdrRespVO.OutDtlVO vo = objectMapper.map(dtl, WfOutHdrRespVO.OutDtlVO.class);
                            vo.setName(vw.getNameDisplay());
                            vo.setDeptid(vw.getDeptDescr());
                            return vo;
                        }
                ).collect(Collectors.toList()));
        //外出事由
        fillBaseWfInfo(user, outHdr, respVO);
        return buildRespone(respVO, false);
    }

    /**
     * 创建外出流程
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/saveOut")
    public BaseResponseVO saveWfOutHdr(@RequestBody PsCWfGoutHdr goutHdr, @SessionGain("user") UserDTO user) {
        logger.info("outHdr save param:{}", goutHdr);
        goutHdr.setcWfEmplid(user.getEmplId());
        //TODO 自己为自己申请提交，是否需要填充其它字段
        goutHdr.setEmplid(user.getEmplId());

        if (!valid(goutHdr)) {
            return buildRespone(BaseRetCode.CODE_ERROR_INPUT_NOT_RIGHT);
        }
        if (!fillBeforeSubmit(goutHdr, user)) return buildRespone(BaseRetCode.CODE_ERROR_GET_TRANSACTION_NBR_FAILED);
        ObjectFieldUtils.handleNullValue(goutHdr);
        PsCWfGoutHdr laveHdr = wfGoutHdrService.saveWfInfo(goutHdr, user);
        if (laveHdr != null) {
            BaseResponseVO resp = submitWf(user, WfTypeEnum.WF_STYPE_OUT.getType(), laveHdr);
            if (!BaseRetCode.CODE_SUCCESS.getRetCode().equals(resp.getRetCode())
                    && WfStatusEnum.WF_STATUS_S.getStatus().equals(laveHdr.getcWfStatus())) {
//				wfGoutHdrService.delWfInfo(laveHdr.getcTransactionNbr());
                logger.error("外出流程申请失败");
            }
            return resp;
        } else {
            return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_APPLY_FAIL);
        }
    }

    private boolean valid(PsCWfGoutHdr g) {
        if (StringUtils.isEmpty(g.getcOutType()) ||
                StringUtils.isEmpty(g.getcOutClass()) ||
                StringUtils.isEmpty(g.getcVehicle()) ||
                StringUtils.isEmpty(g.getcHour()) ||
                StringUtils.isEmpty(g.getcHour1()) ||
                StringUtils.isEmpty(g.getcMinute()) ||
                StringUtils.isEmpty(g.getcMinute1()) ||
                g.getDate1() == null ||
                g.getDate2() == null
        ) {
            return false;
        }
        return true;
    }


    @Override
    protected Set<String> getAuthFileds() {
        return null;
    }
}

class Benchmarking {
    private Integer noYhbNumber;

    private Integer totalNumber;

    private String noYbhRate;

    public Integer getNoYhbNumber() {
        return noYhbNumber;
    }

    public void setNoYhbNumber(Integer noYhbNumber) {
        this.noYhbNumber = noYhbNumber;
    }

    public Integer getTotalNumber() {
        return totalNumber;
    }

    public void setTotalNumber(Integer totalNumber) {
        this.totalNumber = totalNumber;
    }

    public String getNoYbhRate() {
        return noYbhRate;
    }

    public void setNoYbhRate(String noYbhRate) {
        this.noYbhRate = noYbhRate;
    }
}
